package cn.acewill.yxd.yunxundian.ui.schedule;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.CheckSwitchButton;
import cn.acewill.yxd.yunxundian.componet.SelectData;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.sign.EditEvaluationActivity;
import cn.acewill.yxd.yunxundian.ui.sign.LookEvaDetialActivity;
import cn.acewill.yxd.yunxundian.ui.sign.WrittingEvaluationListActivity;
import cn.acewill.yxd.yunxundian.ui.sign.YxdEvaluationListActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by XXX on 2017/6/12.
 */

public class ScheduleModifiActivity extends BaseActivity implements View.OnClickListener{

    protected  YXDAPP yxdapp=new YXDAPP();
    protected  DbManager db = x.getDb(yxdapp.getDaoConfig());
    private TextView modifiTime;
    private int schId;
    private Schedule schedule;
    //隐藏id
    private int hinId;
    private ProgressDialog dialog;

    private String schtime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_detail_view);
        schId=getIntent().getIntExtra("schid",0);
        try {
            initView();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void initView() throws DbException {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView taskTitle = (TextView) findViewById(R.id.TaskTitle);
        TextView taskStartTime = (TextView) findViewById(R.id.taskStartTime);
        this.modifiTime= (TextView) findViewById(R.id.modifiTime);
        modifiTime.setOnClickListener(this);
        LinearLayout hideArea = (LinearLayout) findViewById(R.id.hideArea);
        LinearLayout descLinear = (LinearLayout) findViewById(R.id.descLinear);
        descLinear.setVisibility(View.GONE);
        TextView taskStatus = (TextView) findViewById(R.id.taskStatus);
        TextView location = (TextView) findViewById(R.id.location);
        TextView issueMan = (TextView) findViewById(R.id.issueMan);
        TextView doMan = (TextView) findViewById(R.id.doMan);
        TextView doTask = (TextView) findViewById(R.id.doTask);
        TextView saveModifi = (TextView) findViewById(R.id.saveModifi);
        TextView deleteTask = (TextView) findViewById(R.id.deleteTask);
        CheckSwitchButton hitSwitch = (CheckSwitchButton) findViewById(R.id.hitSwitch);
        schedule=db.selector(Schedule.class).where("ID","=",schId).findFirst();
        if (schedule!=null){

            hinId=schedule.getIsHidden();
            if (hinId==0){
                hitSwitch.setChecked(false);
            }else{
                hitSwitch.setChecked(true);
            }
            if (schedule.getShopID()==-1&&schedule.getIsAssign()==-1){
                doTask.setVisibility(View.GONE);
            }
            hitSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked){
                        hinId=1;

                    }else{
                        hinId=0;
                    }
                }
            });

            if(schedule.getStates()>2)
            {
                doTask.setText("查看");
            }

            taskTitle.setText(schedule.getTitle());
            taskStartTime.setText(schedule.getSchStartTime().replace("T"," "));
            schtime=schedule.getSchStartTime().replace("T"," ");
            if (schedule.getStates()<=1){
                taskStatus.setText("任务状态：任务尚未开始");
            }else if (schedule.getStates()==2){
                taskStatus.setText("任务状态：任务进行中");
                hideArea.setVisibility(View.GONE);
            }else if (schedule.getStates()==3){
                taskStatus.setText("任务状态：任务已提交");
                hideArea.setVisibility(View.GONE);
            }else{
                taskStatus.setText("任务状态：任务已完成");
                hideArea.setVisibility(View.GONE);
            }

            Shop shop=db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
            if (shop!=null && shop.getAddress()!=null&&!TextUtils.isEmpty(shop.getAddress())){
                location.setText("地点："+shop.getAddress());
            }else{
                location.setText("地点：暂未设置");
            }

            Employee employe=db.selector(Employee.class).where("ID","=",schedule.getStartUserId()).findFirst();
            if (employe.getFirstName()!=null&&!TextUtils.isEmpty(employe.getFirstName())){
                issueMan.setText("发布人："+employe.getFirstName());
            }else{
                issueMan.setText("发布人：暂未设置");
            }

            Employee emp=db.selector(Employee.class).where("ID","=",schedule.getToUserId()).findFirst();
            if (employe.getFirstName()!=null&&!TextUtils.isEmpty(emp.getFirstName())){
                doMan.setText("执行人："+emp.getFirstName());
            }else{
                doMan.setText("执行人：暂未设置");
            }

            doTask.setOnClickListener(this);
            deleteTask.setOnClickListener(this);
            saveModifi.setOnClickListener(this);
        }else{
            showToast(this,"日程不存在或已删除");
            finish();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.modifiTime:
                //修改时间
                SelectData data=new SelectData(ScheduleModifiActivity.this,true);
                data.showAtLocation(modifiTime, Gravity.BOTTOM,0,0);
                data.setDateClickListener(new SelectData.OnDateClickListener() {
                    @Override
                    public void onClick(String year, String month, String day, String hour, String minute) {
                        String str=year+"-"+month+"-"+day+" "+hour+":"+minute;
                        modifiTime.setText(str);
                    }
                });
                break;
            case R.id.doTask:
                if(schedule!=null) {
                    if(schedule.getStates()<3) {
//                        startActivity(new Intent(this, WrittingEvaluationListActivity.class).putExtra("rrschid", schId));
                        startActivity(new Intent(this, EditEvaluationActivity.class).putExtra("schId",schId));
                    }
                    else
                    {
                        //查看评估
                        Intent in=new Intent(this,LookEvaDetialActivity.class)
                                .putExtra("schid",schedule.getID());
                        startActivity(in);
                    }
                }
                break;
            case R.id.deleteTask:
                //判断status是否小于等于1
                if (schedule.getStates()<=1){

                    MaterialDialogUtils.showMaterialDialog(this, "是否确定删除当前日程", "确定", "取消", true,false,
                            new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                    deleteMyTask();
                                }
                            }, new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                }
                            });
                } else{
                    BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,"当前任务已开始，不能删除");
                }

                break;
            case R.id.saveModifi:
                //判断是否被修改

                String time=modifiTime.getText().toString().trim();
                int hid=schedule.getIsHidden();
                //如果日程状态为1,0，modifitime会显示，加入这个判断
                if (schedule.getStates()<=1) {
                    if(!TextUtils.isEmpty(time)){
                        SaveMyModifi(time);
                    }else{
                        //time 是空的就去判断id是否修改
                        if (hid!=hinId){

                            SaveMyModifi(schtime);
                        }else{
                            BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,"未做修改");
                        }
                    }
                }else{
                    if (hid!=hinId){
                        SaveMyModifi(schtime);
                    }else{
                        BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,"未做修改");
                    }
                }

                break;
        }
    }

    public void deleteMyTask(){
        final Map<String,String> map=new HashMap<>();
        map.put("task","delSchById");
        map.put("schid",schId+"");
        try {
            dialog=new ProgressDialog(this);
            dialog.setMessage("正在删除中...");
            dialog.show();
            dialog.setCanceledOnTouchOutside(false);
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode==KeyEvent.KEYCODE_BACK){
                        return true;
                    }else{
                        return false;
                    }
                }
            });
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] res=result.split("\\|");
                    if (res[0].equals("200")){
                        dialog.setMessage("删除成功，数据同步中...");
                        try {
                            db.delete(schedule);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        //发送广播
                        Intent in=new Intent();
                        in.setAction(ScheduleActivity.refresh_Schedule);
                        in.putExtra("result",1);
                        sendBroadcast(in);
                        dialog.dismiss();
                        finish();
                    }else{
                        if (res.length>1){
                            BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,res[1]);
                        }else{
                            BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,"删除失败");
                        }
                        dialog.dismiss();
                    }
                }
                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,"删除失败");
                    dialog.dismiss();
                }
            }, map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    Thread t=new Thread() {
//        @Override
//        public void run() {
//            AsynData data = new AsynData();
//            try {
//                data.asynScheduleData(MainActivity.id);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        ;
//    };

    public void SaveMyModifi(final String time){
        Map<String,String> map =new HashMap<>();
        map.put("task","editScheduleBySchid");
        map.put("empid",MainActivity.id+"");
        map.put("schid",schId+"");
        map.put("schtime",time);
        map.put("ishidden",hinId+"");
        dialog=new ProgressDialog(this);
        dialog.setMessage("正在保存中...");
        dialog.show();
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] res=result.split("\\|");
                    if (res[0].equals("200")){
                        dialog.setMessage("保存成功，数据同步中...");
                        String mtime=time.replace(" ","T")+":00";
                        schedule.setSchStartTime(mtime);
                        schedule.setIsHidden(hinId);
                        try {
                            db.saveOrUpdate(schedule);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        //发送广播
                        Intent in=new Intent();
                        in.setAction(ScheduleActivity.refresh_Schedule);
                        in.putExtra("result",1);
                        sendBroadcast(in);

                        dialog.dismiss();
                        finish();
                    }else{
                        dialog.dismiss();
                        BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,res[1]);
                    }
                }

                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(ScheduleModifiActivity.this,"提交失败");
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
